<?php
include_once("config.php");
require_once('../includes/KLogger.php');

define("DB_HOST", $config['DB_HOST']);
define("DB_USER", $config['DB_USER']);
define("DB_PASS", $config['DB_PASS']);
define("DB_NAME", $config['DB_NAME']);
define("LOG_FILE", $config['LOG_FILE']);

class RedFiveServer
{ 

	function  RedFiveServer()
	{
		$this->methodTable = array(
			"postStats" => array(
			  "description" => "post of stats from red5",
			  "access" => "remote",
			  "arguments" => array ("scopedata")
				),
			"initStats" => array(
			  "description" => "server application started",
			  "access" => "remote",
			  "arguments" => array ("applicationnames")				
			  )
		  );
	}
	
	
	function initStats($servername,$applications)
	{	
		$logger = new KLogger(LOG_FILE,KLogger::DEBUG);
		$expiredate = date("Y-m-d G:i:s");
		$scopenames = array();
		
		
		$conn = mysql_connect(DB_HOST, DB_USER, DB_PASS);
		if (!$conn)	return;
		if (!mysql_select_db(DB_NAME))return;
		
		
		/* Check if server instance is registered in database */
		$server_check_query = "SELECT servers.id FROM servers WHERE servers.name = '$servername'";
		$server_check_result = mysql_query($server_check_query);
		if(!$server_check_result){$logger->LogInfo("Query Failed".$server_check_query);return;}
		
		/* Register server if dosent exists in database */
		if(mysql_num_rows($server_check_result)<=0)
		{
			$register_server_query = "INSERT INTO `redfivestats`.`servers` (`id` ,`name`) VALUES (NULL,'$servername')";
			$register_server_result = mysql_query($register_server_query);
			if(!$register_server_result){$logger->LogInfo("Query Failed".$register_server_query);return;}
		}
		
		/* Query server id */
		$server_query = "SELECT servers.id FROM servers WHERE servers.name='$servername'";
		$server_result = mysql_query($server_query);
		if(!$server_result){$logger->LogInfo("Query Failed".$server_query);return;}
		
		
		/* Store server id */
		$record = mysql_fetch_array($server_result, MYSQL_ASSOC);
		$serverid = $record['id'];
		
		/* Fetch scopes for this server */
		$query = "SELECT scopes.name FROM scopes,servers WHERE scopes.serverid = $serverid";
		$result = mysql_query($query);
		if(!$result){$logger->LogInfo("Query Failed".$query);return;}
		
		
		/* Collect scopenames in database*/
		while ($row = mysql_fetch_array($result))
		array_push($scopenames, $row[0]);
		
		
		/* -----------------------------------------
					ADD	SCOPE(S)
		----------------------------------------- */
		for($i=0;$i<sizeof($applications);$i++)
		{
			if(!in_array($applications[$i],$scopenames))
			{
				$application = $applications[$i];
				$query = "INSERT INTO scopes (`id`, `name`, `total_connections`, `active_connections`, `total_subscopes`, `active_subscopes`, `total_clients`, `active_clients`, `total_messages_recieved`, `total_messages_sent`, `total_bytes_recieved`, `total_bytes_sent`, `reg_date`, `serverid`) VALUES (NULL, '$application', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0','$expiredate','$serverid')";
				$scopeadd = mysql_query($query);
				if(!$scopeadd){$logger->LogInfo("Query Failed".$query);return;}
			}
		}
		
		
		/* -----------------------------------------
				CHECK AND REMOVE DEAD SCOPE(S)
		----------------------------------------- */
		for($i=0;$i<sizeof($scopenames);$i++)
		{
			$scopename = $scopenames[$i];
		
			if(!in_array($scopenames[$i],$applications))
			{
				$deleteQuery = "DELETE FROM scopes WHERE scopes.name = '$scopename' AND scopes.serverid = '$serverid'";
				$scoperemove = mysql_query($deleteQuery);
				if(!$scoperemove){$logger->LogInfo("Query Failed".$deleteQuery);return;}
			}
		}
		
		
		/* -----------------------------------------
						CLEAR LOG 
		----------------------------------------- */
		if(file_exists(LOG_FILE))unlink(LOG_FILE);
	
		
		mysql_close($conn);
		unset($logger);
		
		return;
	}	
	
	function postStats($servername,$scopedata)
	{
		$logger = new KLogger(LOG_FILE,KLogger::DEBUG);
		
		$application 				= $scopedata[0];
		$totalconnections 			= intval($scopedata[1]);
		$activeConnections 			= intval($scopedata[2]);
		$totalSubScopes 			= intval($scopedata[3]);
		$activeSubscopes 			= intval($scopedata[4]);
		$totalClients 				= intval($scopedata[5]);
		$activeClients 				= intval($scopedata[6]);
		$clientSentBytes 			= intval($scopedata[7]);
		$clientRecievedBytes 		= intval($scopedata[8]);
		$clientSentMessages 		= intval($scopedata[9]);
		$clientRecievedMessages 	= intval($scopedata[10]);
		$connectionType 			= $scopedata[11];
		$connectionIP 				= $scopedata[12];
		$clientCreationTime			= intval($scopedata[13]);
		
		/* -----------------------------------------
					SCOPE UPDATION 
		----------------------------------------- */
		$conn = mysql_connect(DB_HOST, DB_USER, DB_PASS);
		if (!$conn)	return;
		if (!mysql_select_db(DB_NAME))return;
		
		/* Check if server instance is registered in database */
		$server_check_query = "SELECT servers.id FROM servers WHERE servers.name = '$servername'";
		$server_check_result = mysql_query($server_check_query);
		if(!$server_check_result){$logger->LogInfo("Query Failed".$server_check_query);return;}
		
		
		/* Register server if dosent exists in database */
		if(mysql_num_rows($server_check_result)<=0)
		{
			$register_server_query = "INSERT INTO `redfivestats`.`servers` (`id` ,`name`) VALUES (NULL,'$servername')";
			$register_server_result = mysql_query($register_server_query);
			if(!$register_server_result){$logger->LogInfo("Query Failed".$register_server_query);return;}
		}
		
		
		$query = "SELECT scopes.id,total_messages_recieved,total_messages_sent,total_bytes_recieved,total_bytes_sent FROM scopes WHERE scopes.name = '$application' AND scopes.serverid IN (SELECT servers.id FROM servers WHERE servers.name='$servername')";
		$result = mysql_query($query);
		if(!$result){$logger->LogInfo("Query Failed".$query);return;}
		
		
		$row = mysql_fetch_assoc($result);
		$scope_id = $row['id'];
		$scope_messages_recieved = intval($row['total_messages_recieved']);
		$scope_messages_sent = intval($row['total_messages_sent']);
		$scope_bytes_recieved = floatval($row['total_bytes_recieved']);
		$scope_bytes_sent = floatval($row['total_bytes_sent']);
		
		
		$scope_messages_recieved = $scope_messages_recieved + $clientRecievedMessages;
		$scope_messages_sent = $scope_messages_sent + $clientSentMessages;
		$scope_bytes_recieved = $scope_bytes_recieved + floatval($clientRecievedBytes*0.00098);
		$scope_bytes_sent = $scope_bytes_sent + floatval($clientSentBytes*0.00098);
		
		$updateQuery = "UPDATE scopes SET active_clients='$activeClients',total_clients='$totalClients',active_subscopes='$activeSubscopes',total_subscopes='$totalSubScopes',active_connections='$activeConnections',total_connections='$totalconnections',total_messages_recieved = '$scope_messages_recieved',total_messages_sent='$scope_messages_sent',total_bytes_recieved='$scope_bytes_recieved',total_bytes_sent='$scope_bytes_sent' WHERE scopes.name = '$application' AND scopes.serverid IN (SELECT servers.id FROM servers WHERE servers.name='$servername')";
		$updateResult = mysql_query($updateQuery);
		if(!$updateResult){$logger->LogInfo("Query Failed".$updateQuery);return;}
	
				
		mysql_close($conn);
		unset($logger);
		
		return;
	}
	
} 
?>